package com.example.weblending.utils;

import com.example.weblending.exception.GlobalException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;

@Component
public class MailUtil {

    @Value("${spring.mail.username}")
    private String MAIL_SENDER; //邮件发送者

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private TemplateEngine templateEngine;

    public void sendHTMLMail(String mail,String title,String context) {
        MimeMessage mimeMailMessage = null;
        try {
            mimeMailMessage = javaMailSender.createMimeMessage();
            //true 表示需要创建一个multipart message
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
            mimeMessageHelper.setFrom(MAIL_SENDER);//发送者
            mimeMessageHelper.setTo(mail);//接受者
            mimeMessageHelper.setSubject(title);//邮件标题
            //这里的 true，你加了的话，它发送你HTML页面里面的内容
            //不加的话，默认是 false，它发送整个HTML页面代码
            mimeMessageHelper.setText(context, true);
            //邮件抄送
            javaMailSender.send(mimeMailMessage);//发送邮件
        } catch (Exception e) {
            throw new GlobalException(500,"邮件发送失败，请重试");
        }
    }
    @Async
    public void getOneCode(String name,String code,String mail){
        Context context = new Context();
        context.setVariable("name", name);
        context.setVariable("code", code);
        String emailContent = templateEngine.process("onecode", context);
        this.sendHTMLMail(mail,"重置密码申请通过",emailContent);
    }
    @Async
    public void getVerify(String salt,String name,String id,String mail){
        Context context = new Context();
        //html中填充动态属性值
        context.setVariable("name", name);
        context.setVariable("id",id);
        context.setVariable("salt",salt);
        String emailContent = templateEngine.process("verify", context);
        this.sendHTMLMail(mail,"请验证您的邮箱",emailContent);
    }
}
